package org.batatasframework.support.charts.db;

import java.util.List;
import java.util.Map;

import org.batatasframework.support.charts.ResultArray;
import org.batatasframework.support.charts.ResultArrayReader;

public class DBChartArray implements ResultArray{

	private Object[][] data;
	private String[] labels;
	private String[] axis;
	
	public DBChartArray(ResultArrayReader reader){
		this(reader, false);
	}

	public DBChartArray(ResultArrayReader reader, boolean reverse){
		Map<String, Number[]> maps = reader.getMaps();
		
		if(reverse){
			labels = maps.keySet().toArray(new String[maps.size()]);
			axis = reader.getColumns();
			data = new Object[labels.length][];
			
			int i = 0;
			for(Number[] nus : maps.values()){
				data[i++] = nus;
			}
		}else{
			labels = reader.getColumns();
			axis = maps.keySet().toArray(new String[maps.size()]);
			data = new Object[labels.length][];
			for(int i = 0; i < labels.length; i++){
				data[i] = new Object[axis.length];
			}
			
			int j = 0;
			for(Number[] nus : maps.values()){
				for(int i = 0; i < nus.length; i++){
					data[i][j] = nus[i];
				}
				j++;
			}
		}
	}
	
	private List<Object> items;
	private Object[] columns;
	
	public DBChartArray parse(boolean calculate, boolean reverse){
		
		
		int lenCol = columns.length, lenRow = items.size();
		String[] colNames = new String[lenCol];
		String[] rowNames = new String[lenRow];
		
		for(int i = 0; i < lenCol; i++){
			colNames[i] = columns[i].toString();
		}
		
		int j = 0;//index of row
		if(reverse){
			data = new Object[lenRow][];
			
			/*
			 * C1 C2 C3 C4
			 * 
			 *  A 1 3 2 3
			 *  B 4 3 2 5
			 *  C 5 4 7 2
			 * 
			 * labels = [A,B,C];
			 * 
			 * datas = [[1,4,5],[3,3,4],[2,2,7],[3,5,2]]
			 */
			for(Object it : items){
				Object[] vs = (Object[])it;
				rowNames[j] = vs[0].toString();
				
				data[j] = new Object[lenCol];
				for(int i = 0; i < lenCol; i++){
					data[j][i] = vs[i + 1];
				}
				
				j++;
			}
			
			axis = colNames;
			labels = rowNames;
		}else{
			data = new Object[lenCol][];
			for(int i = 0; i < lenCol; i++){
				data[i] = new Object[lenRow];
			}
			for(Object it : items){
				Object[] vs = (Object[])it;
				rowNames[j] = vs[0].toString();
				
				for(int i = 0; i < lenCol; i++){
					data[i][j] = vs[i + 1];
				}
				
				j++;
			}
			
			axis = rowNames;
			labels = colNames;
		}
		
		return this;
	}

	public DBChartArray(List<Object> items, Object...columns){
		this.items = items;
		this.columns = columns;
	}
	
	@Override
	public String[] getLabels() {
		return labels;
	}

	@Override
	public String[] getAxis() {
		return axis;
	}

	@Override
	public Object[][] getData() {
		return data;
	}

}
